<!-- 库存报表->现存量查询 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <div ref="print" class="credentials-wrapper" id="documents-wrapper">
                <div style="min-height:400px;">
                    <h3 class="text-center">
                        <span class="text-name">现存量查询</span><br>
                    </h3>
                    <!-- 按钮 -->
                    <div class="btn-wrapper clearfix" style="border:none;">
                        <a-row class="text-center clearfix">
                            <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                                <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                                    <div class="btns" @click="searchDynamic">
                                        <a-icon class="btns-icon" type="search" />
                                        <div class="btns-text">查询</div>
                                    </div>
                                </a-col>
                                <!-- <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                                    <div class="btns" @click="printOrder">
                                        <a-icon class="btns-icon" type="printer" />
                                        <div class="btns-text">打印</div>
                                    </div>
                                </a-col>
                                <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                                    <div class="btns" @click="syncFun">
                                        <a-icon class="btns-icon" type="sync" />
                                        <div class="btns-text">刷新</div>
                                    </div>
                                </a-col> -->
                            </a-col>
                            <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                                <!-- <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                                    <div class="btns" @click="printOrder">
                                        <a-icon class="btns-icon" type="printer" />
                                        <div class="btns-text">打印</div>
                                    </div>
                                </a-col> -->
                                <a-col :offset="22" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                                    <div class="btns" @click="exportOrder">
                                        <a-icon class="btns-icon" type="export" />
                                        <div class="btns-text">导出</div>
                                    </div>
                                </a-col>
                            </a-col>
                        </a-row>
                    </div>
                    <section>
                        <a-row>
                            <!-- <condition-box ref="myConditionBox" @callBack="ConditionBoxCallBack"></condition-box> -->
                            <a-col :span="24">
                                <div class="table-box">
                                    <a-table id="bills_tb" :columns="columns" :data-source="dataSource" :pagination="pagination" :rowClassName="rowClassName" @expand="expand" :expandedRowKeys="tableExplandKey" :scroll="{x:600,y:600}" :size="small" bordered>
                                        <template slot="inventoryQuantity" slot-scope="text">
                                            <div>{{text | NumFormat}}</div>
                                        </template>
                                         <template slot="minStorage" slot-scope="text">
                                            <div>{{text | NumFormat}}</div>
                                        </template>
                                         <template slot="maxStorage" slot-scope="text">
                                            <div>{{text | NumFormat}}</div>
                                        </template>
                                        
                                        <template slot="availableQuantity" slot-scope="text">
                                            <div>{{text | NumFormat}}</div>
                                        </template>
                                    </a-table>
                                </div>
                            </a-col>
                        </a-row>
                    </section>
                </div>
            </div>
        </div>
        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

        <!--查询弹窗-->
        <search-wrapper-not-plan ref="searchWrapperRef" @searchPlan="searchPlan">
            <template slot="searchConditions">
                <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">仓库：</label>
                        <div class="filter-control">
                            <div style="background:rgba(0,0,0,0);width:100%;height:28px;z-index:2;position:absolute;top:10px;left:0;" @click="handleSearch('warehouseNameRef')"></div>
                            <a-input-search placeholder="请选择仓库" v-model="warehouseName" size="small" @search="handleSearch('warehouseNameRef')" />

                            <form-search-group ref="warehouseNameRef" :dynamicData="{name:'仓库',val:'warehouse',code:'warehouseId',value:warehouseName}" @clickItem="setValue"></form-search-group>
                        </div>
                    </div>
                </a-col>
                <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">物料分类：</label>
                        <div class="filter-control" ref="inventoryTypeWarpper" id="inventoryTypeId">
                            <a-input size="small" onfocus="this.select()" :style="{'position':'relative','z-index':zIndexType}" v-model="inventoryTypeNameArray" @pressEnter="handleEnter(2)" @change="handleNameChange()" @click="handlInputArchives(4,'inventoryTypeWarpper')" />
                            <search-archives-type v-if="maskArchivesType" ref="searchArchivesRefType" :inventoryDomTop="inventoryDomTop" :inputType="inputType" :inputVal="inputVal" @closeArchives="closeArchives" @check="checkArchives"></search-archives-type>
                            <div class="mask-archives-type" v-show="maskArchivesType" @click="handlCloseArchives"></div>
                        </div>
                    </div>
                </a-col>
                <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">物料编码：</label>
                        <div class="filter-control" ref="inventoryCodeWarpper" id="inventoryCodeId">
                            <a-input-group size="small">
                                <a-row :gutter="8">
                                    <a-col :span="11">
                                        <a-input style="position:relative;z-index:3" size="small" v-model="beginCode" onkeyup="value=value.replace(/[^\d]/g,'')" @pressEnter="handleEnter(1)" @change="handleArchiveChange()" @click="handlInputArchives(1,'inventoryCodeWarpper')" />
                                    </a-col>
                                    <a-col :span="2" class="text-center">至</a-col>
                                    <a-col :span="11">
                                        <a-input style="position:relative;z-index:3" size="small" v-model="endCode" onkeyup="value=value.replace(/[^\d]/g,'')" @pressEnter="handleEnter(1)" @change="handleArchiveChange()" @click="handlInputArchives(2,'inventoryCodeWarpper')" />
                                    </a-col>
                                </a-row>
                            </a-input-group>
                            <searchArchives v-if="maskArchives" ref="searchArchivesRef" :inventoryDomTop="inventoryDomTop" :inputType="inputType" :inputVal="inputVal" @closeArchives="closeArchives" @check="checkArchives"></searchArchives>
                            <div class="mask-archives" v-show="maskArchives" @click="handlCloseArchives"></div>
                        </div>
                    </div>
                </a-col>
                <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">物料名称：</label>
                        <div class="filter-control" ref="inventoryNameWarpper" id="inventoryNameId">
                            <a-input size="small" :style="{'position':'relative','z-index':zIndex}" v-model="inventoryName" @pressEnter="handleEnter(2)" @change="handleNameChange()" @click="handlInputArchives(3,'inventoryNameWarpper')" />
                            <searchArchivesName v-if="maskArchivesName" ref="searchArchivesRefName" :inventoryDomTop="inventoryDomTop" :inputType="inputType" :inputVal="inputVal" @closeArchives="closeArchives" @check="checkArchives"></searchArchivesName>
                            <div class="mask-archives-name" v-show="maskArchivesName" @click="handlCloseArchives"></div>
                        </div>
                    </div>
                </a-col>
                <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">规格型号：</label>
                        <div class="filter-control">
                            <a-input size="small" v-model="inventorySpecification" />
                        </div>
                    </div>
                </a-col>
            </template>
        </search-wrapper-not-plan>
    </div>
</template>
<script>

const dataSource = [];
for (let i = 0; i < 10; i++) {
    let array = {
        date: new Date().getFullYear() + '年' + Number(new Date().getMonth() + 1) + '月',
        abstract: parseInt(Math.random() * 10000),
        name: `${i}100`,
        debitAmount: parseInt(Math.random() * 10000),
        remark: i % 2 == 0 ? '期初余额' : i % 3 == 0 ? '本期发生额' : '本月合计',
        beginAmountDirection: i % 2 == 0 ? '借' : '贷',
        balance: parseInt(Math.random() * 1000),
    }
    dataSource.push(array);
}
import { searchWrapperNotPlan } from '@/components/SearchWrapper/';
import { getAction, exportAction } from "@/api/manage";
import moment from "moment";
import { Controlwidth } from "@/utils/antTableComponents";
import FormSearchGroup from '@/components/Form/FormSearchGroup';

import searchArchives from '@/components/OrderDynamicForm/searchArchives'
import searchArchivesName from '@/components/OrderDynamicForm/searchArchivesName'
import searchArchivesType from '@/components/OrderDynamicForm/searchArchivesType'
import conditionBox from '@/components/Crm/conditionBox';

export default {
    components: {
        FormSearchGroup,        //搜索选择
        searchArchives,         //物料
        searchArchivesName,     //物料名称
        searchArchivesType,
        searchWrapperNotPlan,     //物料分类
        conditionBox,
    },
    data () {
        return {
            //----------↓样式----------
            btn_grid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------

            dataSource: [],
            tableExplandKey: [],//默认展开的行
            columns: [
            {
                title: '物料名称',
                dataIndex: 'inventoryName',
                width: 50,
            }, {
                title: '物料编码',
                dataIndex: 'inventoryCode',
                width: 50,
            }, {
                title: '规格型号',
                dataIndex: 'inventorySpecification',
                width: 50,
            }, {
                title: '仓库名称',
                dataIndex: 'warehouseName',
                width: 50,
            }, 
            {
                title: '货位名称',
                dataIndex: 'inventoryLocationName',
                width: 50,
            }, {
                title: '主计量',
                dataIndex: 'unitName',
                width: 50,
            }, {
                title: '现存量',
                dataIndex: 'inventoryQuantity',
                width: 50,
                align: 'right',
                scopedSlots: {
                    customRender: 'inventoryQuantity'
                }
            },
             {
                title: '最低库存',
                dataIndex: 'minStorage',
                width: 50,
                align: 'right',
                scopedSlots: {
                    customRender: 'minStorage'
                }
            },
             {
                title: '最高库存',
                dataIndex: 'maxStorage',
                width: 50,
                align: 'right',
                scopedSlots: {
                    customRender: 'maxStorage'
                }
            },
                // {
                //     title: '可用量',
                //     dataIndex: 'availableQuantity',
                //     width: 50,
                //     align: 'right',
                //     scopedSlots: {
                //         customRender: 'availableQuantity'
                //     },
                // }
            ],
            pagination: {
                size: "small",
                defaultPageSize: 10,
                current: 1,
                pageSize: 10,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={10}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    this.pagination.current = page;
                    this.getList();
                },
            },
            //物料
            warehouseName: null,//仓库
            warehouseId: null,
            maskArchives: false,
            maskArchivesName: false,
            maskArchivesType: false,
            zIndex: 5,
            zIndexType: 5,
            inputType: null,
            beginCode: null,
            endCode: null,
            inventoryName: null,
            inventoryType: null,
            inventorySpecification: null,
            inventoryTypeNameArray: [],
            inventoryTypeIdArray: [],
            postData: {}
        };
    },
    watch: {
        inventoryTypeNameArray (val) {
            // this.inventoryTypeNameArray = [];
            if (val == null || val == '') {
                this.inventoryTypeIdArray = [];
            }
        }
    },
    updated () {
        Controlwidth("bills_tb", 50);
    },
    created () {
        // this.getList();
    },
    mounted () {
  
    },
    activated () {
        this.getList();
    },
    methods: {
        moment,
        //导出
        exportOrder () {
            exportAction('/inOut/recordMain/storageExportData', this.postData).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "库存报表-现存量.xls");
                document.body.appendChild(link);
                link.click();
            }).catch(error => { });
        },
        printOrder () {
            //打印
            this.$print(this.$refs.print);
        },
        //动态查询搜索条件
        searchDynamic () {
            this.$refs.searchWrapperRef.showModel();
        },
        searchGroup (t) {
            if (t == 1) {
                this.$refs.credentialsSearch.showModal();
            } else {
                //延迟请求
                if (this.setTime) {
                    clearTimeout(this.setTime)
                }
                this.setTime = setTimeout(() => {
                    this.$refs.credentialsSearch.inputSearch();
                }, 500)
            }
        },
        setValue (data) {
            this.name = data.name;
        },
        onChangeBusinessDate (e, v) {
            this.dateTime = v;
        },
        //获取列表
        getList () {
            this.postData = {
                current: this.pagination.current,
                size: this.pagination.pageSize,
                inventoryClassIds: this.inventoryTypeIdArray.join(','),//物料分类ids
                inventoryCodeEnd: this.endCode,
                inventoryCodeStart: this.beginCode,
                inventoryName: this.inventoryName,
                inventorySpecification: this.inventorySpecification,
                warehouseIds: this.warehouseId,
            }
            getAction('/inOut/recordMain/statisticStorageOnHandVo', this.postData).then(response => {
                if (response.code === 200) {
                    console.log(response.data.records);
                    this.dataSource = this.reBuildData(response.data.records) ;
                    this.pagination.total = response.data.total;
                }
            }).catch(error => { });
        },
        reBuildData(data){
            this.tableExplandKey = []; // 利用Array.from将Set结构转换成数组
            let map = new Map();
            for(let i = 0;i < data.length; i++){
                let item = data[i];
                if(item.dataType == 2){
                    item.children = [];
                    item.key = item.inventoryId + '';
                    this.tableExplandKey.push(item.key)
                    map.set(item.inventoryId,item);
                }else{
                    item.key = item.id;
                    let parentItem = map.get(item.inventoryId);
                    parentItem.children.push(item);
                }
            }
            let returnData = [...map.values()];
            console.log("数据重组后，",returnData)
            return returnData;

        },
        expand (expanded, record) {
            //点击展开图标时触发
            let id = record.key;
            if (expanded) {
                this.tableExplandKey.push(id)
            } else {
                this.tableExplandKey.splice(this.tableExplandKey.findIndex(e => e === id), 1);
            }
        },
        rowClassName (record, index) {
            return record.dataType == 2 ? 'changeColorClass' : '';
        },
        //改变分页大小
        changePageSize (e) {
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            Object.assign(this.pagination, {
                current: 1,
                pageSize: size,
            });

            this.getList();
        },
        handleSearch (n) {
            console.log(n);
            this.$refs[`${n}`].showModal();
        },
        setValue (data) {
            console.log(data);
            if (data.codesName == 'warehouseId') {
                //仓库
                this.warehouseName = data.name;
                this.warehouseId = data.id;
            }
        },
        handlInputArchives (type, ref) {
            document.getElementsByClassName('ant-modal-content')[0].style.transform = 'none';

            this.inputType = type;
            if (type == 1 || type == 2) {
                this.maskArchives = true;
                this.zIndex = 1;
                this.zIndexType = 1;
            } else if (type == 3) {
                this.zIndex = 5;
                this.zIndexType = 1;
                this.maskArchivesName = true;
            } else if (type == 4) {
                this.zIndexType = 6;
                this.zIndex = 1;
                this.maskArchivesType = true;
            }
            //获取位置
            console.log(this.$refs[`${ref}`].parentNode.offsetTop);
            let loc = this.$refs[`${ref}`].getBoundingClientRect();
            this.inventoryDomTop = Math.abs(loc.top);
        },
        handleNameChange () {
            //物料名称搜索
            if (this.inventoryName) {
                this.$refs.searchArchivesRefName.inputVal = this.inventoryName;
                this.$refs.searchArchivesRefName.getData(1);
            }
        },
        handleArchiveChange () {
            //物料编码搜索
            console.log(this.inputType)
            if (this.inputType == 1) {
                this.inputVal = this.beginCode;
            } else {
                this.inputVal = this.endCode;
            }
            this.$refs.searchArchivesRef.inputVal = this.inputVal;
            this.$refs.searchArchivesRef.getData(1);
        },
        handleEnter (t) {
            if (t == 1) {
                this.$refs.searchArchivesRef.handleEnter();
            } else {
                this.$refs.searchArchivesRefName.handleEnter();
            }
        },
        closeArchives () {
            this.maskArchives = false;
            this.maskArchivesName = false;
            this.maskArchivesType = false;
        },
        //关闭物料档案弹窗
        handlCloseArchives () {
            document.getElementsByClassName('ant-modal-content')[0].style.transform = 'translate(0px, 0px)';

            if (this.inputType == 1 || this.inputType == 2) {
                this.maskArchives = false;
                this.$refs.searchArchivesRef.closeModel();
            } else if (this.inputType == 3) {
                this.maskArchivesName = false;
                this.$refs.searchArchivesRefName.closeModel();
            } else if (this.inputType == 4) {
                this.maskArchivesType = false;
                this.$refs.searchArchivesRefType.closeModel();
            }
        },
        //物料选择范围-----------------------------------
        checkArchives (data) {
            this.maskArchives = false;
            this.maskArchivesName = false;
            //返回值处理
            const { dataSource } = this;
            if (data[1] == 1) {
                //起始值
                this.beginCode = data[0][0].inventoryCode;
            }
            if (data[1] == 2) {
                //起始值
                this.endCode = data[0][0].inventoryCode;
            }
            if (data[1] == 3) {
                //物料编码名称
                this.inventoryName = data[0][0].inventoryName;
            }
            if (data[1] == 4) {
                //物料分类
                console.log(data[0]);
                let tData = data[0].checkedNodes;
                let typeNameArray = [];
                let typeIdArray = [];
                tData.forEach(item => {
                    typeNameArray.push(item.data.class);
                    typeIdArray.push(item.data.props.id);
                });

                this.inventoryTypeNameArray = typeNameArray.join(';')
                this.inventoryTypeIdArray = typeIdArray;
            }

            this.closeArchives();
        },
        searchPlan () {
            this.pagination.current = 1;
            this.getList();
            this.$refs.searchWrapperRef.cancel();//关闭弹窗
        },
        syncFun () {
            //刷新
            this.getList();
        },
        //查询方案回调
        ConditionBoxCallBack (data) {
            let size = this.postData.page.size;
            if (data)
                this.postData = data;
            Object.assign(this.postData, {
                page: {
                    size,
                    current: 1,
                }
            });
            this.pageList();
        }
    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';

    .credentials-wrapper {
        padding: 10px;
        height: auto;
        overflow-y: auto;
        font-size: 14px;
        .date-tp {
            margin-bottom: 10px;
            .header-tp {
                text-align: left;
            }
        }
        .footer-tp {
            text-align: center;
            margin-top: 10px;
        }

        .text-name {
            // border-bottom: 2px solid rgba(0, 0, 0, 0.8);
            padding-bottom: 5px;
        }

        .bills-box-header {
            display: flex;
            justify-content: space-around;
            .filter {
                display: table;
                width: 280px;
                margin-bottom: 5px;
                .filter-label {
                    display: table-cell;
                    font-weight: normal;
                    max-width: 160px;
                    line-height: 32px;
                    white-space: nowrap;
                    vertical-align: bottom;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }
                .filter-control {
                    display: table-cell;
                    width: 100%;
                }
            }
        }
    }
  
</style>
<style lang="less" scoped>
    .changeColorClass {
        font-weight: bold;
        background-color: #fffceb;
    }
</style>